<template>
  <div class="container">
    <topTitle
      :titleText="titleText"
      @gobackTriser="goBack"
      :back="back"
    ></topTitle>
    <div class="mainCon">
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formData"
        label-width="120px"
      >
        <el-form-item label="巡查类型：" prop="inspectionType">
          <el-select
            v-model="formData.inspectionType"
            placeholder="请选择"
            :disabled="xcTypeDisabled"
            clearable
            class="sWidth"
          >
            <el-option label="日常巡查" value="DAILY"></el-option>
            <el-option label="专项巡查" value="SPECIAL"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模板类别：" prop="type">
          <el-select
            v-model="formData.type"
            placeholder="请选择"
            :disabled="mbTypeDisabled"
            clearable
            class="sWidth"
          >
            <el-option label="非建领域" value="NC"></el-option>
            <el-option label="建设领域" value="CS"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模板名称：" prop="name">
          <el-input
            v-model="formData.name"
            prop="name"
            placeholder="请输入模板名称"
            clearable
            class="lWidth"
          ></el-input>
        </el-form-item>
        <el-form-item label="巡查事项：" prop="ipqcTemplateDetailExpendVOs">
          <!-- <el-input type="hidden" v-model="formData.ipqcTemplateDetailExpendVOs"></el-input> -->
          <el-table
            :data="tableData"
            :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
            highlight-current-row
            stripe
            border
            :row-key="getRowKey"
            @select="selectItem"
            @select-all="selectAll"
            @selection-change="selectionChange"
            ref="multipleTable"
            v-loading="loading"
            style="border: 1px solid #dfe6ec"
          >
            <el-table-column
              align="center"
              type="selection"
              :reserve-selection="true"
              width="55px"
            ></el-table-column>
            <el-table-column
              prop="typeName"
              label="事项类型"
              :formatter="formatTd"
            ></el-table-column>
            <el-table-column
              prop="itemName"
              label="巡查项"
              :formatter="formatTd"
            ></el-table-column>
            <!-- 表格数据为空时，页面显示 -->
            <div slot="empty" v-show="isShow">
              <emptyTable emptyText="暂无相关信息"></emptyTable>
            </div>
          </el-table>
          <!-- filterField为搜索条件 -->
          <Pagination
            ref="pagination"
            @getList="getTableList"
            :requestUrl="requestUrl"
            @getpageNo="getpageNo"
            @getpageSize="getpageSize"
          ></Pagination>
        </el-form-item>
        <div class="submitBox">
          <el-button class="commonBut" @click="toDetail">预览模板</el-button>
          <el-button
            v-sdc
            :loading="isAdd"
            type="primary"
            class="commonBut saveBtn"
            @click.native="saveForm"
            >保存</el-button
          >
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'patrolTemplateAdd',
  data() {
    return {
      titleText: '新建巡查模板',
      isAdd: false,
      back: true,
      formData: {
        inspectionType: '', //巡查类型。
        type: '', //模板类型
        name: '', //模板名称
        ipqcTemplateDetailExpendVOs: '',
      },
      formRules: {
        name: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
        inspectionType: [
          { required: true, message: '巡查类型不能为空', trigger: 'change' },
        ],
        type: [
          { required: true, message: '模板类型不能为空', trigger: 'change' },
        ],
        ipqcTemplateDetailExpendVOs: [
          { required: true, message: '巡查事项不能为空', trigger: 'blur' },
        ],
      },
      requestUrl: 'api-gov/ipqc/item/expand/listnowhere',
      loading: true,
      isShow: false,
      tableData: [], //表格数据
      pageSize: 20,
      pageNo: 1,
      btnChangeEnable: false,
      edit: '',
      templateId: '',
      selected: [],
      selectItems: [],
      xcTypeDisabled: false,
      mbTypeDisabled: false,
    }
  },
  created() {
    this.edit = this.$route.query.edit
    if (this.edit == 'Add') {
      this.titleText = '新建巡查模板'
      this.xcTypeDisabled = false
      this.mbTypeDisabled = false
      this.$nextTick(function () {
        this.$refs.pagination.getTableListData()
      })
    } else {
      this.titleText = '编辑模板'
      this.templateId = this.$route.query.templateId
      this.xcTypeDisabled = true
      this.mbTypeDisabled = true
      this.getTemplate(this.templateId)
    }
  },
  methods: {
    getpageSize(val) {
      this.pageSize = val
    },
    getpageNo(val) {
      this.pageNo = val
    },
    getTableList(data) {
      this.tableData = data
      this.loading = false
      if (this.tableData.length < 1) {
        this.isShow = true
      }
      if (this.edit === 'Update') {
        this.onOldAjglId(this.selectItems)
      }
    },
    goBack() {
      this.$router.push('/home/patrolTemplate/patrolTemplateList')
      this.$store.commit('GOBACK_NAME', {
        oldUrl: '/home/patrolTemplate/patrolTemplateList',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    getRowKey(row) {
      return row.itemId
    },
    toDetail() {
      let type = this.formData.type
      if (!type) {
        this.$message({
          type: 'error',
          message: '请选择模板类型',
        })
        return
      }
      let select = this.myConcat(this.selectItems, this.selected)
      if (type == 'NC') {
        this.$router.push({
          path: '/home/patrolTemplate/patrolTemplateDetailFj',
          name: 'patrolTemplateDetailFj',
          query: {
            page: 'patrolTemplateAdd',
            selectItems: select,
          },
        })
      }
      if (type == 'CS') {
        this.$router.push({
          path: '/home/patrolTemplate/patrolTemplateDetailJz',
          name: 'patrolTemplateDetailJz',
          query: {
            page: 'patrolTemplateAdd',
            selectItems: select,
          },
        })
      }
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/patrolTemplate/patrolTemplateList',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    saveForm() {
      this.isAdd = true
      let url = 'api-gov/ipqc/template/expand/add'
      if (this.edit == 'Update') {
        url = 'api-gov/ipqc/template/expand/edit'
        this.formData.id = this.templateId
      }
      let select = this.myConcat(this.selectItems, this.selected)
      let templates = []
      select.forEach((item) => {
        let obj = { itemId: item.itemId }
        templates.push(obj)
      })
      this.formData.ipqcTemplateDetailExpendVOs = templates
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.btnChangeEnable = true
          this.axios({
            method: 'post',
            url: url,
            data: this.formData,
            headers: {
              'Content-Type': 'application/json',
            },
          })
            .then((response) => {
              if (!response.data.hasError) {
                this.$message({
                  type: 'success',
                  message: '保存成功',
                })
                this.isAdd = false
                this.$router.push({
                  path: '/home/patrolTemplate/patrolTemplateList',
                  name: 'patrolTemplateList',
                })
                this.$store.commit('CHANGE_SLIDER_NAME', {
                  oldUrl: '/home/patrolTemplate/patrolTemplateList',
                  newUrl: this.$router.currentRoute.fullPath,
                })
              } else {
                this.$message({
                  type: 'error',
                  message: response.data.errorMsg,
                })
                this.btnChangeEnable = false
              }
            })
            .catch((error) => {})
        } else {
          this.isAdd = false
          return false
        }
      })
    },
    selectItem(selection, row) {
      // console.log(selection)
      var selected = selection.length && selection.indexOf(row) !== -1
      if (selected) {
        this.selectItems.push(row)
      } else {
        this.selectItems.forEach((item, i) => {
          if (item.itemId === row.itemId) {
            this.selectItems.splice(i, 1)
          }
        })
      }

      return
      console.log(selection)
      this.selectItems.forEach((item, idx) => {
        if (item.itemId === row.itemId) {
          console.log('0000')
          this.selectItems.splice(idx, 1)
        }
      })
      console.log('2222')
    },
    selectAll(selection) {
      // console.log(selection)
      this.selectItems = selection
      // this.isAllSelect = !this.isAllSelect;
      // if(this.isAllSelect){
      //     this.employeeList.forEach(row => {
      //         this.$refs.multipleTable.toggleRowSelection(row, true)
      //     })
      // }else {
      // this.$refs.multipleTable.clearSelection()
      // }
    },
    selectionChange(selection) {
      // this.selected = selection;
      // console.log(selection)
    },
    myConcat(arr1, arr2) {
      let json = arr1.concat(arr2)
      let newJson = []
      json.forEach((item) => {
        let flag = true
        newJson.forEach((nItem) => {
          if (item.itemId === nItem.itemId) {
            flag = false
          }
        })
        if (flag) {
          newJson.push(item)
        }
      })
      return newJson
    },
    onOldAjglId(oldIds) {
      if (oldIds.length > 0) {
        oldIds.forEach((item) => {
          this.tableData.forEach((tableItem) => {
            if (item.itemId === tableItem.itemId) {
              this.$refs.multipleTable.toggleRowSelection(tableItem, true)
            }
          })
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    getTemplate(templateId) {
      this.axios({
        method: 'post',
        url: 'api-gov/ipqc/template/expand/detail',
        data: {
          id: templateId,
        },
      })
        .then((response) => {
          this.$nextTick(function () {
            this.$refs.pagination.getTableListData()
          })
          if (!response.data.hasError) {
            let templateInfo = response.data.result
            this.formData.inspectionType = templateInfo.inspectionType
            this.formData.type = templateInfo.type
            this.formData.name = templateInfo.name
            this.selectItems = templateInfo.ipqcTemplateDetailExpendVOs
          } else {
            this.$message({
              type: 'error',
              message: response.data.errorMsg,
            })
            this.btnChangeEnable = false
          }
        })
        .catch((error) => {})
    },
  },
}
</script>

<style scoped lang="less">
.mainCon {
  padding: 40px 24px;
}
.valWidth {
  width: 300px;
}
.submitBox {
  margin-top: 20px;
  text-align: center;
}
</style>
